package com.itcam.otcbackend.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itcam.otcbackend.annotation.AuthCheck;
import com.itcam.otcbackend.common.BaseResponse;
import com.itcam.otcbackend.common.DeleteRequest;
import com.itcam.otcbackend.constant.UserConstant;
import com.itcam.otcbackend.enums.ErrorCode;
import com.itcam.otcbackend.exception.BusinessException;
import com.itcam.otcbackend.model.dto.user.*;
import com.itcam.otcbackend.model.po.User;
import com.itcam.otcbackend.model.vo.LoginUserVO;
import com.itcam.otcbackend.model.vo.UserVO;
import com.itcam.otcbackend.service.UserService;
import com.itcam.otcbackend.utils.ResultUtils;
import com.itcam.otcbackend.utils.ThrowUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
	
     /**
     * 用户注册接口
     *
     * @param userRegisterRequest 用户注册请求对象，包含用户注册所需信息
     * @return 包含注册用户 ID 的基础响应对象
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        // 检查请求对象是否为空，若为空则抛出参数错误异常
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        // 从请求对象中获取用户账号
        String userAccount = userRegisterRequest.getUserAccount();
        // 从请求对象中获取用户密码
        String userPassword = userRegisterRequest.getUserPassword();
        // 从请求对象中获取确认密码
        String checkPassword = userRegisterRequest.getCheckPassword();
        // 调用用户服务的注册方法进行用户注册，并获取注册结果（用户 ID）
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        // 将注册结果封装到成功响应对象中并返回
        return ResultUtils.success(result);
    }

    /**
     * 用户登录接口
     *
     * @param userLoginRequest 用户登录请求对象，包含用户登录所需信息
     * @param request HttpServletRequest对象，用于处理HTTP请求
     * @return 包含登录用户信息的基础响应对象
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        // 检查请求对象是否为空，若为空则抛出参数错误异常
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        // 从请求对象中获取用户账号
        String userAccount = userLoginRequest.getUserAccount();
        // 从请求对象中获取用户密码
        String userPassword = userLoginRequest.getUserPassword();
        // 调用用户服务的登录方法进行用户登录，并获取登录用户信息
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        // 将登录用户信息封装到成功响应对象中并返回
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 获取当前用户登录
     * @param request
     * @return
     */
    @PostMapping("/get/login")
    @ApiOperation("获取当前用户登录")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(loginUser));
    }

    /**
     * 用户退出
     * @param request
     * @return
     */
    @ApiOperation("用户退出")
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 创建用户
     * @param userAddRequest
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("创建用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtil.copyProperties(userAddRequest, user);
        // 默认密码是 12345678
        final String DEFAULT_PASSWORD = "12345678";
        String encryptPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据id获取用户（仅管理员）
     * @param id
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("根据id获取用户")
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(null == user, ErrorCode.FORBIDDEN_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据id获取包装类
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    @ApiOperation("根据id获取包装类")
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVo(user));
    }

    /**
     * 根据id删除用户（仅管理员）
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("根据id删除用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (null == deleteRequest || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(result);
    }

    /**
     * 更新用户（仅管理员）
     */
    @PostMapping("/update")
    @ApiOperation("更新用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取用户封装列表（仅管理员）
     *
     * @param userQueryRequest 查询请求参数
     */
    @PostMapping("/list/page/vo")
    @ApiOperation("分页获取用户封装列表")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        // 检查查询请求参数是否为空，若为空则抛出参数错误异常
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 从查询请求参数中获取当前页码
        long current = userQueryRequest.getCurrent();
        // 从查询请求参数中获取每页记录数
        long pageSize = userQueryRequest.getPageSize();
        // 调用用户服务的分页方法，根据当前页码、每页记录数和查询条件获取用户分页数据
        Page<User> userPage = userService.page(
                new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest)
        );
        // 创建一个新的用户封装分页对象，设置当前页码、每页记录数和总记录数
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        // 调用用户服务的方法，将用户列表转换为用户封装列表
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        // 将用户封装列表设置到用户封装分页对象中
        userVOPage.setRecords(userVOList);
        // 将用户封装分页对象封装到成功响应对象中并返回
        return ResultUtils.success(userVOPage);
    }


}


